# 检查项目文件编码脚本
# 确保所有源代码文件都是 UTF-8 编码（无 BOM）

$files = Get-ChildItem -Recurse -File -Include *.ts,*.js,*.json,*.md,*.sql,*.txt,.env* `
    | Where-Object { 
        $_.FullName -notlike "*node_modules*" -and 
        $_.FullName -notlike "*dist*" -and
        $_.FullName -notlike "*\.git*"
    }

$utf8NoBomCount = 0
$utf8BomCount = 0
$otherCount = 0
$errors = @()

Write-Host "检查文件编码..." -ForegroundColor Cyan
Write-Host ""

foreach ($file in $files) {
    try {
        $bytes = [System.IO.File]::ReadAllBytes($file.FullName)
        
        if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) {
            $utf8BomCount++
            Write-Host "⚠️  $($file.Name): UTF-8 with BOM" -ForegroundColor Yellow
            $errors += $file.FullName
        } else {
            # 尝试读取为 UTF-8 验证
            try {
                $content = [System.IO.File]::ReadAllText($file.FullName, [System.Text.Encoding]::UTF8)
                $utf8NoBomCount++
            } catch {
                $otherCount++
                Write-Host "❌ $($file.Name): 非 UTF-8 编码" -ForegroundColor Red
                $errors += $file.FullName
            }
        }
    } catch {
        $otherCount++
        Write-Host "❌ $($file.Name): 检查失败 - $_" -ForegroundColor Red
        $errors += $file.FullName
    }
}

Write-Host ""
Write-Host "检查结果:" -ForegroundColor Cyan
Write-Host "  ✅ UTF-8 (无 BOM): $utf8NoBomCount" -ForegroundColor Green
Write-Host "  ⚠️  UTF-8 (有 BOM): $utf8BomCount" -ForegroundColor Yellow
Write-Host "  ❌ 其他编码: $otherCount" -ForegroundColor Red

if ($errors.Count -gt 0) {
    Write-Host ""
    Write-Host "需要修复的文件:" -ForegroundColor Yellow
    $errors | ForEach-Object { Write-Host "  - $_" }
    exit 1
} else {
    Write-Host ""
    Write-Host "✅ 所有文件都是 UTF-8 编码（无 BOM）" -ForegroundColor Green
    exit 0
}

